package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysMemberGroup;
import org.dromara.system.domain.SysUserEmptyOrderRecords;
import org.dromara.system.domain.bo.SysUserEmptyOrderRecordsBo;
import org.dromara.system.domain.bo.SysUserPurseBo;
import org.dromara.system.domain.vo.SysUserEmptyOrderRecordsVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.enums.SysUserFreezePointsRecordsEnum;
import org.dromara.system.mapper.SysUserEmptyOrderRecordsMapper;
import org.dromara.system.service.ISysMemberGroupService;
import org.dromara.system.service.ISysUserEmptyOrderRecordsService;
import org.dromara.system.service.ISysUserFreezePointsRecordsService;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 空单记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserEmptyOrderRecordsServiceImpl extends
    ServiceImpl<SysUserEmptyOrderRecordsMapper, SysUserEmptyOrderRecords> implements ISysUserEmptyOrderRecordsService {

    private final ISysUserFreezePointsRecordsService sysUserFreezePointsRecordsService;
    private final ISysUserService userService;
    private final ISysMemberGroupService sysMemberGroupService;


    /**
     * 查询空单记录
     *
     * @param id 主键
     * @return 空单记录
     */
    @Override
    public SysUserEmptyOrderRecordsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询空单记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 空单记录分页列表
     */
    @Override
    public TableDataInfo<SysUserEmptyOrderRecordsVo> queryPageList(SysUserEmptyOrderRecordsBo bo, PageQuery pageQuery) {
        if(ObjectUtil.isNull(bo.getUserId())){
            bo.setUserId(LoginHelper.getUserId());
        }
        LambdaQueryWrapper<SysUserEmptyOrderRecords> lqw = buildQueryWrapper(bo);
        Page<SysUserEmptyOrderRecordsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的空单记录列表
     *
     * @param bo 查询条件
     * @return 空单记录列表
     */
    @Override
    public List<SysUserEmptyOrderRecordsVo> queryList(SysUserEmptyOrderRecordsBo bo) {
        LambdaQueryWrapper<SysUserEmptyOrderRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserEmptyOrderRecords> buildQueryWrapper(SysUserEmptyOrderRecordsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserEmptyOrderRecords> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserEmptyOrderRecords::getId);
        lqw.eq(bo.getUserId() != null, SysUserEmptyOrderRecords::getUserId, bo.getUserId());
        lqw.eq(bo.getAmount() != null, SysUserEmptyOrderRecords::getAmount, bo.getAmount());
        return lqw;
    }

    /**
     * 新增空单记录
     *
     * @param bo 空单记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserEmptyOrderRecordsBo bo) {
        SysUserEmptyOrderRecords add = MapstructUtils.convert(bo, SysUserEmptyOrderRecords.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改空单记录
     *
     * @param bo 空单记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserEmptyOrderRecordsBo bo) {
        SysUserEmptyOrderRecords update = MapstructUtils.convert(bo, SysUserEmptyOrderRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserEmptyOrderRecords entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除空单记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    @Override
    public Boolean freezePointsTopUp(SysUserEmptyOrderRecordsBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())){
            bo.setUserId(LoginHelper.getUserId());
        }
        List<SysUserEmptyOrderRecords> list = lambdaQuery().eq(SysUserEmptyOrderRecords::getUserId, bo.getUserId()).list();
        BusinessException.notEmpty(list, "恭喜您，参与活动成功！请勿重复报名！");
        SysUserVo sysUserVo = userService.selectUserById(bo.getUserId());
        Long memberGroupId = sysUserVo.getMemberGroupId();
        SysMemberGroup sysMemberGroup = sysMemberGroupService.getById(memberGroupId);
        //充值待返积分
        SysUserPurseBo sysUserPurseBoFrozen = SysUserPurseBo.builder()
            .userId(bo.getUserId())
            .type(SysUserFreezePointsRecordsEnum.ORDER_POINTS.getCode())
            .freezePoints(sysMemberGroup.getComplianceRewards())
            .build();
        sysUserFreezePointsRecordsService.updateUserFreezePoints(CollUtil.newArrayList(sysUserPurseBoFrozen));
        //增加下单记录
        insertByBo(SysUserEmptyOrderRecordsBo.builder()
            .userId(bo.getUserId())
            .amount(sysMemberGroup.getComplianceRewards())
            .build());
        return Boolean.TRUE;
    }
}
